package com.ttdevs.app;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

/**
 * 
 * 内存图片的LRU缓存，初始化传入两个参数：分配的内存大小和是否启用本地SDCard缓存
 * 
 * @author ttdevs 2014年2月24日
 * 
 * @version 1.0
 */
public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageCache {

	private BitmapSDCardCache manager = null;
	private boolean mIsSDCardCache = false;

	public BitmapLruCache(int maxSize, boolean isSDCardCache) {
		super(maxSize);
		mIsSDCardCache = isSDCardCache;

		if (mIsSDCardCache) {
			manager = new BitmapSDCardCache();
			manager.start();
		}
	}

	@Override
	protected int sizeOf(String key, Bitmap value) {
		// TODO value.getByteCount();
		return value.getRowBytes() * value.getHeight();
	}

	@Override
	public Bitmap getBitmap(String url) {
		Bitmap tbm = get(url);
		if (tbm != null) {
			return tbm;
		}
		if (mIsSDCardCache) {
			tbm = manager.loadBitmap(url);
			if (tbm != null) {
				put(url, tbm);
			}
		}
		return tbm;
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		put(url, bitmap);
		if (mIsSDCardCache) {
			manager.saveBitmap(url, bitmap);
		}
	}

	public void quit() {
		if (mIsSDCardCache && manager != null) {
			manager.quit();
		}
	}
}